//
//  HomePageDetailViewController.m
//  InSuger
//
//  Created by dllo on 15/11/28.
//  Copyright © 2015年 Dior_3g. All rights reserved.
//

#import "HomePageDetailViewController.h"

@interface HomePageDetailViewController ()<UITableViewDataSource, UITableViewDelegate, HomePageDetailTableViewCellDelegate, WXApiDelegate>

@property(nonatomic, strong) UITableView *tableView;
@property(nonatomic, strong) NSMutableArray *tableArray;
@property(nonatomic, strong) NSMutableDictionary *tableDic;

@property(nonatomic, strong) UIImageView *detailImageView;
@property(nonatomic, strong) UILabel *detailLabel;

@property(nonatomic, strong) UIView *weixinView;
@property(nonatomic, strong) UIButton *weixin;
@property(nonatomic, strong) UIButton *friend;
@property(nonatomic, strong) UIButton *weiBo;

@end

@implementation HomePageDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self connetDB];
    [self createTable];
    [self create];
    [self createWeiXin];
    self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
    self.navigationItem.title = @"专题详情";
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName : [UIColor whiteColor]}];
    self.tableView.backgroundColor = [UIColor whiteColor];
    
    //      -----------------------------       下拉刷新    -----------------------------
    MJRefreshGifHeader *header = [MJRefreshGifHeader headerWithRefreshingTarget:self refreshingAction:@selector(headerData)];
    self.tableView.mj_header = header;
    
}

#pragma mark    下拉刷新
- (void)headerData {
    
    [self.tableView.mj_header beginRefreshing];
    [self create];
    
}


#pragma mark    连接数据库
- (void)connetDB {
    
    [[DataBaseHandle shareDataBaseHandle] openDB];
    
    SelectModel result = [[DataBaseHandle shareDataBaseHandle] isHaveInTable:self.model];
    
    if (result == InTable) {
        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"已收藏" style:UIBarButtonItemStylePlain target:self action:@selector(click:)];
    } else if (result == NotInTable){
        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"收藏" style:UIBarButtonItemStylePlain target:self action:@selector(click:)];
    } else {
        NSLog(@"错误");
    }
    
}

#pragma mark    创建tableView视图
- (void)createTable {
    
    self.tableView = [[UITableView alloc] initWithFrame:self.view.frame style:UITableViewStylePlain];
    [self.view addSubview:self.tableView];
    
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.center.equalTo(self.view);
        make.size.mas_equalTo(self.view);
        
    }];

    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    self.tableView.bounces = NO;
    [self.tableView registerClass:[HomePageDetailTableViewCell class] forCellReuseIdentifier:@"reuse"];
    
    UIView *detailView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT / 100 * 60)];
    self.tableView.tableHeaderView = detailView;
    
    self.detailImageView = [[UIImageView alloc] initWithFrame:CGRectMake(WIDTH / 100 , HEIGHT / 100, WIDTH / 100 * 98, HEIGHT / 100 * 30)];
    [detailView addSubview:self.detailImageView];
    
    self.detailLabel = [[UILabel alloc] initWithFrame:CGRectMake(WIDTH / 100 * 3, HEIGHT / 100 * 32, WIDTH / 100 * 94, HEIGHT / 100 * 18)];
    [detailView addSubview:self.detailLabel];
    self.detailLabel.numberOfLines = 0;
    self.detailLabel.font = [UIFont systemFontOfSize:15];
    
    @weakify(self);
    [self addColorChangedBlock:^{
        @strongify(self);
        self.detailLabel.nightTextColor = [UIColor whiteColor];
        detailView.nightBackgroundColor = UIColorFromRGB(0x343434);
        detailView.normalBackgroundColor = [UIColor whiteColor];
    }];

}

#pragma mark    收藏按钮设置
- (void)click: (UIBarButtonItem *)button {
    
    if ([button.title isEqualToString:@"收藏"]) {
        
        [AlertController createAlertTitle:@"提示信息" alertMessage:@"是否收藏" cancelTitle:@"取消" doneTitle:@"确认" viewController:self block:^(id block) {
            
            [[DataBaseHandle shareDataBaseHandle] saveModelInDB:self.model];
            button.title = @"已收藏";
        }];
        
    } else {
        
        [AlertController createAlertTitle:@"提示信息" alertMessage:@"是否取消收藏" cancelTitle:@"取消" doneTitle:@"确认" viewController:self block:^(id block) {
            
            [[DataBaseHandle shareDataBaseHandle] deleteModelInDB:self.model];
            button.title = @"收藏";
        }];
        
    }
}

#pragma mark    数据解析
- (void)create {
    
    NSString *string = @"%2C2&track_deviceid=A5849E0F-EF33-4B83-80B1-0B846EE0DB3B&track_user_id=1457728&v=7";
    
    [AFN getdataWithString:[NSString stringWithFormat:@"http://open3.bantangapp.com/topic/info?app_installtime=1445349591.654459&app_versions=4.2.2&channel_name=appStore&client_id=bt_app_ios&client_secret=9c1e6634ce1c5098e056628cd66a17a5&id=%@&oauth_token=8e93baa2127b39cbf64d15bfee8cff56&os_versions=9.0.2&screensize=640&statistics_uv=0&track_device_info=iPhone6%@]", self.model.tableId, string] block:^(id block) {
        
        self.tableDic = block[@"data"];
        self.tableArray = [NSMutableArray array];
        
        self.tableArray = [HomePageDetailModel baseModelByArr:self.tableDic[@"product"]];

        [self.tableView reloadData];
        [self.tableView.mj_header endRefreshing];
    }];
}

#pragma mark    tableView两个必须实现的方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.tableArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    self.tableView.rowHeight = HEIGHT * 0.8;
    
    HomePageDetailTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"reuse" forIndexPath:indexPath];
    
    [self.detailImageView sd_setImageWithURL:[NSURL URLWithString:self.tableDic[@"pic"]]];
    
    self.detailLabel.text = self.tableDic[@"desc"];
    
    cell.delegate = self;
    cell.model = self.tableArray[indexPath.row];
    return cell;
}

#pragma mark    微信的视图与按钮
- (void)createWeiXin {
    
    self.weixinView = [[UIView alloc] initWithFrame:CGRectMake(WIDTH / 100, HEIGHT / 10 * 7, WIDTH / 100 * 98, HEIGHT / 10 * 2.8)];
    [self.view addSubview:self.weixinView];
    self.weixinView.hidden = YES;
    
    self.weixin = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.weixinView addSubview:_weixin];
    
    self.friend = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.weixinView addSubview:_friend];
    
    self.weiBo = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.weixinView addSubview:_weiBo];
}

- (void)share:(HomePageDetailModel *)model {
    
    self.weixinView.hidden = NO;
    self.weixinView.backgroundColor = [UIColor colorWithWhite:0.7 alpha:0.8];
    self.weixinView.layer.cornerRadius = 10;

    [_weixin setImage:[UIImage imageNamed:@"weixin.png"] forState:UIControlStateNormal];
    _weixin.frame = CGRectMake(WIDTH / 100 * 5, HEIGHT / 100 * 2, WIDTH / 100 * 12.6, HEIGHT / 100 * 7.2);
    [_weixin addTarget:self action:@selector(weiXin:) forControlEvents:UIControlEventTouchUpInside];
    _weixin.backgroundColor = [UIColor whiteColor];
    _weixin.layer.cornerRadius = 24;

    [_friend setImage:[UIImage imageNamed:@"friend.png"] forState:UIControlStateNormal];
    _friend.frame = CGRectMake(WIDTH / 100 * 25, HEIGHT / 100 * 2, WIDTH / 100 * 12.6, HEIGHT / 100 * 7.2);
    [_friend addTarget:self action:@selector(friend:) forControlEvents:UIControlEventTouchUpInside];
    _friend.backgroundColor = [UIColor whiteColor];
    _friend.layer.cornerRadius = 24;
    
    [_weiBo setImage:[UIImage imageNamed:@"weibo.png"] forState:UIControlStateNormal];
    _weiBo.frame = CGRectMake(WIDTH / 100 * 45, HEIGHT / 100 * 2, WIDTH / 100 * 12.6, HEIGHT / 100 * 7.2);
    [_weiBo addTarget:self action:@selector(weiBo:) forControlEvents:UIControlEventTouchUpInside];
    _weiBo.backgroundColor = [UIColor whiteColor];
    _weiBo.layer.cornerRadius = 24;
    
    
    self.detailModel = [[HomePageDetailModel alloc] init];
    self.detailModel = model;
    
}

#pragma mark    分享的方法
- (void)weiXin:(HomePageDetailModel *)model {

    model = self.detailModel;
    NSLog(@"%@", model);
    SendMessageToWXReq* req = [[SendMessageToWXReq alloc] init];
    req.text = model.share_url;
    req.bText = YES;
    req.scene = WXSceneSession;
    
    [WXApi sendReq:req];
}

- (void)friend:(HomePageDetailModel *)model {
    
    model = self.detailModel;
    NSLog(@"%@", model);
    SendMessageToWXReq* req = [[SendMessageToWXReq alloc] init];
    req.text = model.share_url;
    req.bText = YES;
    req.scene = WXSceneTimeline;
    
    [WXApi sendReq:req];
}

- (void)weiBo:(HomePageDetailModel *)model {
    
    model = self.detailModel;
    WBMessageObject *message = [WBMessageObject message];
    message.text = model.share_url;
    WBSendMessageToWeiboRequest *request = [WBSendMessageToWeiboRequest requestWithMessage:message];
    [WeiboSDK sendRequest:request];
    
}


#pragma mark    点击后隐藏分享视图
- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    
    self.weixinView.hidden = YES;
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
